package com.changgou.file.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.file.util.FastDFSClient;
import com.changgou.file.util.FastDFSFile;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @Author ${张瀚化}
 * @Date 2020/12/10 21:33
 * @Since 1.0.0
 */

@RestController
@RequestMapping("/file")
public class FileController {
    private static org.slf4j.Logger logger = LoggerFactory.getLogger(FastDFSClient.class);
    @PostMapping
    public Result upload(@RequestParam("file") MultipartFile file){
        String fileName =null;
          //获取文件全名，形式如：123.jpg
        try {
            fileName = file.getOriginalFilename();
            //获取扩展名，形式如 ： .jpg
            String extName = fileName.substring(fileName.lastIndexOf("."));
            //获取文件内容
            byte[] fileContenxt = file.getBytes();

            //创建一个FastDFSFile 对象
            FastDFSFile fastDFSFile = new FastDFSFile(fileName,fileContenxt,extName);
            //上传文件
            String[] upload = FastDFSClient.upload(fastDFSFile);
            if(upload!=null&&upload.length==2){
                 //获取文件组名
                String groupName = upload[0];
                //获取文件储存服务器的远程存储路径
                String remoteFilePath = upload[1];
                //TODO 将路径存储到数据库表中


             String url = FastDFSClient.getTrackerUrl()+groupName+"/"+remoteFilePath;
             logger.info("上传成功,url:{}",url);
             return new Result(true, StatusCode.OK,"上传成功",url);
            }else {
                logger.error("上传失败,fileName:{}",fileName);
                return new Result(false, StatusCode.ERROR,"上传失败");

            }
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("上传失败,fileName:{}",fileName);
            return new Result(false, StatusCode.ERROR,"上传失败");
        }
    }

}
